#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <iostream>
#include <unistd.h>
#include <cstring>

using namespace std;

const char *pathname = "/home/zh";
int proj_id = 12;
int size = 4096;

key_t getkey()//封装ftok
{
    key_t key = ftok(pathname, proj_id);
    if (key < 0)
    {
        perror("ftok");
        exit(-1);
    }
    cout << "key值被成功创建,key:" << key << endl;
    return key;
}

int getshm(int shmflg)
{
    key_t key = getkey();
    int shmid = shmget(key, size, shmflg);
    if (shmid < 0)
    {
        perror("shmget");
        exit(-1);
    }
    cout << "共享内存标识码被成功创建，shmid:" << shmid << endl;
    return shmid;
}

int creatnewshm()//只想用最新的共享内存来进程通信
{
    return getshm(IPC_CREAT|IPC_EXCL|0666);//为了能够观察到变化，所以要保证共享内存的权限
}

int getoldshm()//获取一个已经存在的共享内存进行通信
{
    return getshm(IPC_CREAT);
}